package cn.com.twoke.application.game.mario.core.ecs.level.loader;

import cn.com.twoke.application.game.mario.core.ecs.level.data.BindLevelLoader;
import cn.com.twoke.application.game.mario.core.ecs.level.data.LevelData;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ReflectUtil;

import java.util.HashMap;
import java.util.Map;

public class LevelLoaderFactory {

    private static final Map<Class<? extends LevelData>, LevelLoader> LEVEL_LOADER_MAP = new HashMap<>();


    public static LevelLoader get(Class<? extends LevelData> clazz) {
        if (LEVEL_LOADER_MAP.containsKey(clazz))  return LEVEL_LOADER_MAP.get(clazz);
        BindLevelLoader annotation = AnnotationUtil.getAnnotation(clazz, BindLevelLoader.class);
        Class<? extends LevelLoader<? extends LevelData>> levelLoaderClass = Opt.ofNullable(annotation).map(BindLevelLoader::value)
                .orElseThrow(() -> new RuntimeException("关卡数据没有绑定关卡加载器"));
        LevelLoader<? extends LevelData> levelLoader = ReflectUtil.newInstance(levelLoaderClass);
        LEVEL_LOADER_MAP.put(clazz, levelLoader);
        return levelLoader;
    }

}
